/* eslint-disable consistent-return */
/* eslint-disable array-callback-return */
import React from 'react';
import { connect } from 'dva';
import { UploadOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Row, Col, Input, Select, AutoComplete, Upload, Button, message, Spin } from 'antd';
import { requestHeadersMd5 } from '@/utils/utils';
import HOCSelect from '@/components/AntDesign/Select';

const FormItem = Form.Item;
const { Option } = Select;
const { Search } = Input;
@connect(({ login }) => ({
  login,
}))
@Form.create()
class BasicForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      uploadUrl: '/csApi/fileServer/uploadFile',
      downloadUrl: '/csApi/fileServer/downloadFile',
      affixList: [],
      custList: [],
      custServiceList: [], // 负责人
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'custedit/fetchRespUserList',
      payload: {},
    }).then(res => {
      if (res.success && res.data) {
        res.data.map(item => {
          const temp = item;
          temp.userName = `${item.orgName}- ${item.userName}`;
        });
        this.setState({
          custServiceList: res.data,
        });
      } else {
        this.setState({ custServiceList: [] });
      }
    });
  }

  // 搜索客户:主数据接口
  searchCust = value => {
    const { dispatch } = this.props;
    dispatch({
      type: 'custedit/searchCust',
      payload: { name: value },
    }).then(res => {
      if (res.success && res.data) {
        this.setState({
          custList: res.data,
        });
      } else {
        this.setState({ custList: [] });
      }
    });
  };

  // 通过社会统一信用代码查询客户
  searchCustByCode = value => {
    const { dispatch, getCustName, getCustNametwo, form } = this.props;
    dispatch({
      type: 'custedit/searchCustByCode',
      payload: { uniCreditCode: value },
    }).then(res => {
      if (res && res.success && res.data) {
        getCustName(res.data.name);
        getCustNametwo(res.data.uniCreditCode);
        const getFieldsList = form.getFieldsValue();
        Object.keys(getFieldsList).forEach(key => {
          if (res.data[key]) {
            if (key === 'corpNature' || key === 'industryCode') {
              form.setFieldsValue({
                [key]: { key: `${res.data[key]}`, mdCustId: null },
              });
            } else {
              form.setFieldsValue({ [key]: res.data[key], mdCustId: null });
            }
          }
        });
      }
    });
  };

  // 选择某一客户
  selectCust = custId => {
    let custInfo = null;
    const { custList } = this.state;
    const { getCustName, getCustNametwo, form } = this.props;
    custList.map(item => {
      if (custId === item.mdCustId) {
        custInfo = item;
      }
    });
    getCustName(custInfo.name);
    getCustNametwo(custInfo.uniCreditCode);
    const getFieldsList = form.getFieldsValue();
    Object.keys(getFieldsList).forEach(key => {
      if (custInfo[key]) {
        if (key === 'corpNature' || key === 'industryCode') {
          form.setFieldsValue({ [key]: { key: `${custInfo[key]}`, mdCustId: null } });
        } else {
          form.setFieldsValue({ [key]: custInfo[key], mdCustId: null });
        }
      }
    });
  };

  slelce = e => {
    let lllo = '';
    const { custList } = this.state;
    const { getCustName, getCustNametwo } = this.props;
    custList.map(item => {
      if (e === item.mdCustId) {
        getCustName(item.name);
        getCustNametwo(item.uniCreditCode);
        lllo = 1;
      }
    });
    if (lllo !== 1) {
      getCustName(e);
    }
  };

  slelcetwo = e => {
    const { getCustNametwo } = this.props;
    getCustNametwo(e);
  };

  // 负责人的下拉
  getCurrentPrmiName = value => {
    const { getCustPrim } = this.props;
    getCustPrim(value);
  };

  // 文件限制大小
  beforeUpload = () => {};

  getData = (value, id) => {
    const { form } = this.props;
    if (id) {
      form.setFieldsValue({ [id]: value });
      this.setState({ [id]: value });
    }
  };

  // 文件上传
  changeUpload = (info, listContFile) => {
    let { fileList } = info;
    const { file } = info;
    const { downloadUrl } = this.state;
    const { getFileInfo } = this.props;
    const newData = listContFile.map(item => ({ ...item }));
    if (file.status === 'done' && file.response.success) {
      const fileId = file.response.data.split('|')[0];
      const fileName = file.response.data.split('|')[1];
      fileList.map(files => {
        const temp = files;
        temp.url = `${downloadUrl}?fileId=${fileId}&fileName=${fileName}`;
        temp.linkProps = { download: `${fileName}` };
      });
      newData.push({
        uid: file.uid,
        custAffixId: fileId,
        affixName: fileName,
      });
      this.setState({ affixList: newData });
      getFileInfo(newData);
      message.success('文件上传成功！');
    } else {
      fileList = [];
      if ((file.status === 'done' && !file.response.success) || file.status === 'error') {
        message.error('上传失败！');
      }
      return fileList;
    }
  };

  // 移除文件
  removeFile = (file, listContFile) => {
    const { getFileInfo } = this.props;
    const newData = listContFile.filter(item => item.uid !== file.uid);
    this.setState({ affixList: newData });
    getFileInfo(newData);
  };

  render() {
    const { uploadUrl, affixList, custServiceList, custList, loading } = this.state;
    const {
      isCompany,
      suppReplaceCorpId,
      supplyList,
      form: { getFieldDecorator },
      comTypeList,
      industryCodeList,
      isRequired,
    } = this.props;
    // 表单布局
    const xl = { span: 8 };
    const lg = { span: 8 };
    const md = { span: 8 };
    const sm = 24;
    const colProps = { xl, lg, md, sm };
    // 下拉选项
    // 公司类型
    const comTypeOL = comTypeList.map(options => (
      <Option key={options.itemCode}>{options.itemName}</Option>
    ));

    // 行业分类
    const industryCodeOL = industryCodeList.map(options => (
      <Option key={options.itemCode}>{options.itemName}</Option>
    ));
    // 文件上传
    const uploadProps = {
      beforeUpload: info => this.beforeUpload(info, affixList),
      action: uploadUrl,
      headers: requestHeadersMd5(),
      onChange: info => this.changeUpload(info, affixList),
      onRemove: file => this.removeFile(file, affixList),
    };
    // 客户名称的列表
    const options = custList.map(opt => (
      <Option key={opt.mdCustId} value={opt.mdCustId}>
        {opt.name}
      </Option>
    ));
    return (
      <Card
        title={<span style={{ fontWeight: 'bolder' }}>客户基本信息</span>}
        bordered={false}
        style={{ marginBottom: 24 }}
      >
        <Spin tip="Loading..." spinning={loading}>
          <Form layout="vertical">
            <Row gutter={64}>
              <Col {...colProps}>
                <FormItem label="签约方">
                  {getFieldDecorator('suppId', {
                    rules: [{ required: true, message: '请输入' }],
                    initialValue: suppReplaceCorpId || undefined,
                  })(
                    <HOCSelect
                      placeholder="请选择"
                      onChange={e => isCompany(e)}
                      showSearch
                      optionFilterProp="children"
                    >
                      {supplyList.map(one => (
                        <Option key={one.suppId} value={one.suppId}>
                          {one.name}
                        </Option>
                      ))}
                    </HOCSelect>
                  )}
                </FormItem>
              </Col>
              <Col md={8} sm={24}>
                <FormItem label="客户名称">
                  {getFieldDecorator('name', {
                    rules: [{ required: true, message: '请输入' }],
                  })(
                    <AutoComplete
                      dataSource={options}
                      onSelect={this.selectCust}
                      onChange={this.slelce}
                    >
                      <Search
                        placeholder="请输入关键字检索"
                        maxLength={100}
                        onSearch={value => this.searchCust(value)}
                      />
                    </AutoComplete>
                  )}
                </FormItem>
              </Col>
              <Col {...colProps}>
                <FormItem label="统一社会信用代码">
                  {/* pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{18}$/ */}
                  {getFieldDecorator('uniCreditCode', {
                    rules: [
                      {
                        required: true,
                        message: '18位的数字与字母组合',
                        pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{18}$/,
                      },
                    ],
                  })(
                    // <Input placeholder="请准确输入18位统一社会信用代码" />
                    <AutoComplete onChange={this.slelcetwo}>
                      <Search
                        placeholder="请输入关键字检索"
                        maxLength={100}
                        onSearch={value => this.searchCustByCode(value)}
                      />
                    </AutoComplete>
                  )}
                </FormItem>
              </Col>
              {/* <Col {...colProps}>
                <FormItem label="客户编号">
                  {getFieldDecorator('no', {
                    rules: [{ required: true, message: '请输入不超过15位的纯数字' }],
                  })(
                    <InputNumber
                      min={1}
                      maxLength={15}
                      placeholder="请输入纯数字"
                      style={{ width: '100%' }}
                    />
                  )}
                </FormItem>
              </Col> */}
            </Row>
            <Row gutter={64}>
              <Col {...colProps}>
                <FormItem label="公司类型">
                  {getFieldDecorator('corpNature', {
                    rules: [{ required: true, message: '请选择' }],
                  })(
                    <HOCSelect
                      placeholder="请输入关键字检索"
                      style={{ width: '100%' }}
                      allowClear
                      labelInValue
                      showSearch
                      optionFilterProp="children"
                    >
                      {comTypeOL}
                    </HOCSelect>
                  )}
                </FormItem>
              </Col>
              <Col {...colProps}>
                <FormItem label="行业分类">
                  {getFieldDecorator('industryCode', {
                    rules: [{ required: true, message: '请选择' }],
                  })(
                    <HOCSelect
                      placeholder="请输入关键字检索"
                      style={{ width: '100%' }}
                      allowClear
                      labelInValue
                      showSearch
                      optionFilterProp="children"
                    >
                      {industryCodeOL}
                    </HOCSelect>
                  )}
                </FormItem>
              </Col>
              <Col {...colProps}>
                <FormItem label="财务NC编码">
                  {getFieldDecorator('fmNcNo', {
                    rules: [
                      {
                        // required: isRequired,
                        message: '请输入不超过15位的纯数字',
                        pattern: /^\d{1,15}$/,
                      },
                    ],
                  })(<Input placeholder="请输入" maxLength={15} />)}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={64}>
              <Col {...colProps}>
                <FormItem label="办公地址">
                  {getFieldDecorator('detailAddress', {
                    rules: [{ required: false, message: '请输入的内容必须在1-100个字' }],
                  })(<Input placeholder="请输入" maxLength={100} />)}
                </FormItem>
              </Col>
              <Col {...colProps}>
                <FormItem label="工作邮箱">
                  {getFieldDecorator('email', {
                    rules: [{ type: 'email', message: '应为邮箱格式且长度不能超过50' }],
                  })(<Input placeholder="请输入" maxLength={50} />)}
                </FormItem>
              </Col>
              <Col {...colProps}>
                <FormItem label="负责人">
                  {getFieldDecorator('primId', {
                    rules: [{ required: true, message: '请选择' }],
                  })(
                    <HOCSelect
                      placeholder="请输入关键字检索"
                      style={{ width: '100%' }}
                      labelInValue
                      showSearch
                      optionFilterProp="children"
                      onChange={this.getCurrentPrmiName}
                    >
                      {custServiceList.map(option => (
                        <Option key={option.userId}>{option.userName}</Option>
                      ))}
                    </HOCSelect>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={64}>
              <Col {...colProps}>
                <FormItem label="备注">
                  {getFieldDecorator('remark', {
                    rules: [{ required: false, message: '请输入的内容必须在1-200个字' }],
                  })(<Input placeholder="请输入" maxLength={200} />)}
                </FormItem>
              </Col>
              <Col {...colProps}>
                <Form.Item label="附件">
                  {getFieldDecorator('custAffixList', {
                    rules: [{ required: false, message: '请输入' }],
                  })(
                    <Upload {...uploadProps} beforeUpload={this.beforeUpload}>
                      {affixList.length < 5 ? (
                        <Button>
                          <UploadOutlined /> 上传附件
                        </Button>
                      ) : null}
                    </Upload>
                  )}
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </Spin>
      </Card>
    );
  }
}
const BasicFormList = Form.create()(BasicForm);
export default BasicFormList;
